package com.googlecode.lookie.platform.osgi;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ApplicationObjectSupport;

public class OsgiMessageSource
    extends ApplicationObjectSupport
    implements MessageSource
{

    private MessageSource[] contributions;

    public MessageSource[] getContributions()
    {
        if ( true )
        {
            List<MessageSource> list = new ArrayList<MessageSource>();

            Object osgiBeans = getApplicationContext().getBean( "messageSources" );
            for ( Object bean : ( (List<?>) osgiBeans ) )
            {
                MessageSource source = (MessageSource) bean;
                list.add( source );
            }

            contributions = list.toArray( new MessageSource[list.size()] );
        }

        return contributions;
    }

    public String getMessage( MessageSourceResolvable resolvable, Locale locale )
        throws NoSuchMessageException
    {
        for ( MessageSource contrib : getContributions() )
        {
            String msg = null;
            try
            {
                msg = contrib.getMessage( resolvable, locale );
            }
            catch ( NoSuchMessageException e )
            {
            }
            if ( msg != null )
            {
                return msg;
            }
        }
        throw new NoSuchMessageException( "", locale );
    }

    public String getMessage( String code, Object[] args, Locale locale )
        throws NoSuchMessageException
    {
        String msg = null;

        for ( MessageSource contrib : getContributions() )
        {
            try
            {
                msg = contrib.getMessage( code, args, locale );
            }
            catch ( NoSuchMessageException e )
            {
            }
            if ( msg != null )
            {
                break;
            }
        }

        if ( msg == null )
        {
            throw new NoSuchMessageException( code, locale );
        }

        return msg;
    }

    public String getMessage( String code, Object[] args, String defaultMessage, Locale locale )
    {
        String msg = null;

        try
        {
            msg = getMessage( code, args, locale );
        }
        catch ( NoSuchMessageException e )
        {
            msg = defaultMessage;
        }

        return msg;
    }

}
